var vm = new Vue({
    el: '#example',
    data: {
        message: 'Hello'
    }
    //计算属性
    , computed: {
        // 计算属性的 getter
        // reversedMessage: function () {
        //     // `this` 指向 vm 实例
        //     return this.message.split('').reverse().join('')
        // }
        now: function () {
            return Date.now()
        }
    }
    //计算属性缓存 vs 方法
    // 在组件中
    , methods: {
        reversedMessage: function () {
            return this.message.split('').reverse().join('')
        }
    }
})

var vm2 = new Vue({
    el: '#demo',
    data: {
        firstName: 'Foo',
        lastName: 'Bar',
    }
    , computed: {
        // fullName: function () {
        //     return this.firstName + ' ' + this.lastName;
        // }
        fullName: {
            get: function () {
                return this.firstName + ' ' + this.lastName;
            },
            set: function (newName) {
                var names = newName.split(' ')
                this.firstName = names[0]
                this.lastName = names[names.length - 1]
            }
        }
    }
});

var watchEl = new Vue({
    el: '#watch-example',
    data: {
        question: '',
        answer: 'I cannot give you an answer until you ask a question!',
        imgUrl: 'https://yesno.wtf/assets/no/1-c7d128c95c1740ec76e120146c870f0b.gif'
    }
    , watch: {
        //如果question发生改变，这个函数就会执行
        question: function (newQuestion, oldQuestion) {
            console.log("newQuestion:" + newQuestion + " " + "oldQuestion:" + oldQuestion);
            this.answer = 'Waiting for you to stop typing...'
            this.debouncedGetAnswer()
        }
    }
    , created: function () {
        console.log("创建侦听器，并初始化相关参数");
        // `_.debounce` 是一个通过 Lodash 限制操作频率的函数。
        // 在这个例子中，我们希望限制访问 yesno.wtf/api 的频率
        // AJAX 请求直到用户输入完毕才会发出。想要了解更多关于
        // `_.debounce` 函数 (及其近亲 `_.throttle`) 的知识，
        // 请参考：https://lodash.com/docs#debounce
        this.debouncedGetAnswer = _.debounce(this.getAnswer, 500);
    }
    , methods: {
        getAnswer: function () {
            if (this.question.indexOf('?') === -1) {
                this.answer = 'Questions usually contain a question mark. ;-)'
                return
            }
            this.answer = 'Thinking...'
            var vm = this
            axios.get('https://yesno.wtf/api')
                .then(function (response) {
                    console.log(response);
                    console.log(response.data.image);
                    vm.answer = _.capitalize(response.data.answer)
                    vm.imgUrl = response.data.image;
                })
                .catch(function (error) {
                    vm.answer = 'Error! Could not reach the API. ' + error
                })
        }
    }
})